#include "filesTabUI.h"

filesTabUI::filesTabUI(QWidget *parent) : QWidget(parent)
{
    initUI();
}

filesTabUI::~filesTabUI(void)
{
    tabWidget->deleteLater();
    hBoxLayout->deleteLater();
}

void filesTabUI::initUI(void)
{
    // tab的初始化以及添加
    tabWidget = new QTabWidget;

    downloadTab.tabName = tr("正在下载");
    downloadTab.iconPath = tr(":/images/tabDown");
    downloadTab.cList.setSpacing(4);
    tabWidget->addTab(&(downloadTab.cList),
                      QIcon(downloadTab.iconPath),
                      downloadTab.tabName
                      );

    finishedTab.tabName = tr("已完成");
    finishedTab.iconPath = tr(":/images/tabF");
    finishedTab.cList.setSpacing(4);
    tabWidget->addTab(&(finishedTab.cList),
                      QIcon(finishedTab.iconPath),
                      finishedTab.tabName
                      );

    deletedTab.tabName = tr("回收站");
    deletedTab.iconPath = tr(":/images/tabL");
    deletedTab.cList.setSpacing(4);
    tabWidget->addTab(&(deletedTab.cList),
                      QIcon(deletedTab.iconPath),
                      deletedTab.tabName
                      );

    hBoxLayout = new QHBoxLayout(); // 将tab水平排布
    hBoxLayout->addWidget(tabWidget);
    this->setLayout(hBoxLayout);
}


// 在“下载标签页”中添加新任务
void filesTabUI::slotCreateNewTask(struct newTaskMessage m)
{
    // 1. 新建Item, 并添加到List
    QListWidgetItem* item = new QListWidgetItem;
    item->setSizeHint(QSize(100, 80));
    downloadTab.cList.addItem(item);
    downloadTab.elementPlace << item;

    // 2. 新建文件的Widget控件
    uiItemWidget *itemWidget = new uiItemWidget;
    itemWidget->setDownloadStateUI();
    downloadTab.elementContent << itemWidget;

    // 3. 给Item设置Widget
    downloadTab.cList.setItemWidget(item, itemWidget);
       itemWidget->taskInit(m);


    // 设置删除item的槽
    connect(itemWidget, &uiItemWidget::deleteCompletely, \
                     this, &filesTabUI::deleteCompletely);
    connect(itemWidget, &uiItemWidget::deleteEasyly, \
                     this, &filesTabUI::deleteEasyly);
    connect(itemWidget,  &uiItemWidget::returnTask, \
            this, &filesTabUI::returnTask);
    connect(itemWidget, &uiItemWidget::finishedTask, \
            this, &filesTabUI::finishedTask);

}

// 在“下载标签页”中还原任务
void filesTabUI::restoreTask()
{
    // 1. 新建Item, 并添加到List
    QListWidgetItem* item = new QListWidgetItem;
    item->setSizeHint(QSize(100, 80));
    downloadTab.cList.addItem(item);
    downloadTab.elementPlace << item;

    // 2. 新建文件的Widget控件
    uiItemWidget *itemWidget = new uiItemWidget;
    itemWidget->setDownloadStateUI();
    downloadTab.elementContent << itemWidget;

    // 3. 给Item设置Widget
    downloadTab.cList.setItemWidget(item, itemWidget);
     itemWidget->resumeInit();


    // 设置删除item的槽
    connect(itemWidget, &uiItemWidget::deleteCompletely, \
                     this, &filesTabUI::deleteCompletely);
    connect(itemWidget, &uiItemWidget::deleteEasyly, \
                     this, &filesTabUI::deleteEasyly);
    connect(itemWidget,  &uiItemWidget::returnTask, \
            this, &filesTabUI::returnTask);
    connect(itemWidget, &uiItemWidget::finishedTask, \
            this, &filesTabUI::finishedTask);

}
void filesTabUI::deletDownload(DownloadController* downloadController)
{

        downloadController->m_File->flush();
        downloadController->m_File->close();
        downloadController->m_File->deleteLater();

        qDebug() << "Download finished";
        for(auto i : downloadController->m_ThreadHadDownload)
        {
            qDebug() << i;
        }
        //线程全部退出
        for(auto i : downloadController->m_ThreadList)
        {
            i->quit();
        }
        //清空文件
        QFile file("C:\\Users\\CHD\\Desktop\\download.txt");
        if (file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
            QTextStream stream(&file);
            stream << "";
            file.close();
        }

}
// 从Tab中完全移除Item
void filesTabUI::deleteCompletely(void)
{

    // Returns a pointer to the object that sent the signal
    uiItemWidget* itemWidget = qobject_cast<uiItemWidget*>(sender());
    if (itemWidget == nullptr)    
        return;
    deletDownload(itemWidget->fManager->m_pDownLoader);
   //qDebug()<<"Tab move Item";
    // 查找位置
    int index = -1;
    int count = 0;

    struct tabList *pList = nullptr;
    if (itemWidget->fManager->fMessage.type == DOWNLOADING)
        pList = &downloadTab;
    else if (itemWidget->fManager->fMessage.type == FINISHED)
        pList = &finishedTab;
    else
        pList = &deletedTab;

    for (auto iter = (*pList).elementContent.begin(); iter != (*pList).elementContent.end(); ++iter)
    {
        if (*iter == itemWidget)
        {
            index = count;
            break;
        }

        count++;
    }
    if (index < 0)
        return;

    // 从List中移除
    (*pList).elementPlace.removeAt(index);
    (*pList).elementContent.removeAt(index);

    // 释放内存
    QListWidgetItem* item = (*pList).cList.takeItem(index);
    delete item;
    itemWidget->deleteLater();

}

void filesTabUI::transferUI( tabList *deletList, uiItemWidget*itemWidget,tabList* targetList,int num)
{
    // 查找位置
    int index = -1;
    int count = 0;
    for (auto iter = deletList->elementContent.begin(); iter != deletList->elementContent.end(); ++iter)
    {
        if (*iter == itemWidget)
        {
            index = count;
            break;
        }

        count++;
    }
    if (index < 0)
        return;

    // 从List中移除
    deletList->elementPlace.removeAt(index);
    deletList->elementContent.removeAt(index);

    // 这个采用之前可正常使用
    QListWidgetItem* item = deletList->cList.takeItem(index);

    //转移到downloadTab
    uiItemWidget* itemWidgetNew = new uiItemWidget;

// 下载文件->回收站
    if(num==1)
    {
         itemWidgetNew->againInit(itemWidget->fManager->fMessage);
         itemWidgetNew->fManager->fMessage.type = DELETED;
         itemWidgetNew->setDeletedStateUI();
    }
// 回收站->正在下载
    else if(num==2)
    {
        fileMessages tmpfile=itemWidget->fManager->fMessage;
        itemWidgetNew->againInit(tmpfile);
        itemWidgetNew->m_pProgressBar->setValue(0);
        QString downloadStr = "%1 / %2";
        downloadStr = downloadStr.arg(0).arg(tmpfile.fileSize);
        itemWidgetNew->m_pProgressTag->setText(downloadStr);
        itemWidgetNew->fManager->fMessage.type = DOWNLOADING;
        itemWidgetNew->m_pPlayButton->setEnabled(true);
        //清空文件
        QString m_outputFile = "C:\\Users\\CHD\\Desktop\\download.txt";
        std::ofstream outFile(m_outputFile.toStdString(), std::ios::trunc);//先清空
            if (outFile.is_open()) {
                outFile <<itemWidget->fManager->fMessage.url.toStdString() << '\n';
                outFile << itemWidget->fManager->fMessage.savePath.toStdString() << '\n';
                outFile << itemWidget->fManager->fMessage.fileName.toStdString() << '\n';
                outFile << "0" << '\n';
                outFile.close();
                qDebug() << "Successfully saved download info to ";
            } else {
                qDebug() << "Failed to open file " ;
            }

      }
// 正在下载->已完成
    else if(num==3)
    {
      itemWidgetNew->againInit(itemWidget->fManager->fMessage);
      itemWidgetNew->fManager->fMessage.type = FINISHED;
      itemWidgetNew->setFinishedStateUI();
    }

     targetList->cList.addItem(item);
     targetList->elementPlace << item;
     targetList->elementContent << itemWidgetNew;
     targetList->cList.setItemWidget(item, itemWidgetNew);

    // 设置删除item的槽
    connect(itemWidgetNew, &uiItemWidget::deleteCompletely, \
                     this, &filesTabUI::deleteCompletely);
    connect(itemWidgetNew, &uiItemWidget::deleteEasyly, \
                     this, &filesTabUI::deleteEasyly);
    connect(itemWidgetNew,  &uiItemWidget::returnTask, \
            this, &filesTabUI::returnTask);
    connect(itemWidgetNew, &uiItemWidget::finishedTask, \
            this, &filesTabUI::finishedTask);

    itemWidget->deleteLater();

}

// 下载文件->回收站
void filesTabUI::deleteEasyly(void)
{
    uiItemWidget* itemWidget = qobject_cast<uiItemWidget*>(sender());
    if (itemWidget == nullptr)
         return;
    struct tabList *pList = nullptr;
        if (itemWidget->fManager->fMessage.type == DOWNLOADING)
        {
            //qDebug()<<"DOWNLOADING";
            pList = &downloadTab;
        }
        else if (itemWidget->fManager->fMessage.type == FINISHED)
        {
            //qDebug()<<"FINISHED";
            pList = &finishedTab;
        }
        else
            return; // 如果是回收站的文件，按取消就默认还在那里
       transferUI(pList,itemWidget,&deletedTab,1);
    //itemWidget->fManager->fMessage.type = DELETED;

}


// 回收站->正在下载
void filesTabUI::returnTask()
{
    // Returns a pointer to the object that sent the signal
    uiItemWidget* itemWidget = qobject_cast<uiItemWidget*>(sender());
    if (itemWidget == nullptr)
        return;
    //itemWidget->fManager->fMessage.type =DOWNLOADING;
    transferUI(&deletedTab,itemWidget,&downloadTab,2);
}

// 正在下载->已完成
void filesTabUI::finishedTask()
{
    // Returns a pointer to the object that sent the signal
    uiItemWidget* itemWidget = qobject_cast<uiItemWidget*>(sender());
    if (itemWidget == nullptr)
        return;
    //itemWidget->fManager->fMessage.type = FINISHED;
    transferUI(&downloadTab,itemWidget,&finishedTab,3);

}
